#include "PlayerJoined.hh"
#include "ClientState.hh"
#include "XmlClient.hh"
#include "../Exception.hh"

using namespace Network;

spPlayerJoined PlayerJoined::construct(QString const& playerName) {
    return spPlayerJoined(new PlayerJoined(playerName));
}

spPlayerJoined PlayerJoined::construct(QDomElement const& message) {
    QDomElement const nameElem = message.firstChildElement("name");
    QDomNode const nameNode = nameElem.firstChild();
    QDomText const nameText = nameNode.toText();
    QString const nameStr = nameText.nodeValue();

    if (nameElem.isNull())
        throw NonFatalProtocolError("init.player_joined.name missing");

    if (!nameNode.isText())
        throw NonFatalProtocolError("init.player_joined.name invalid");

    return construct(nameStr);
}

PlayerJoined::PlayerJoined(QString const& playerName):
    InitMessage(),
    playerName(playerName) {}

void PlayerJoined::process_on_client(XmlClient& client) {
	ClientState s = client.get_state();
	if (s == START || s == AUTHENTICATED || s == INIT_GET_GAME_LIST_SENT)
		throw ProtocolError("init.playerjoined unexpected");


}

QDomDocument PlayerJoined::to_xml() const {
    QDomDocument doc;
    QDomElement init = doc.createElement("init");
    QDomElement playerJoined = doc.createElement("player_joined");
    QDomElement nameElem = doc.createElement("name");
    QDomText nameText = doc.createTextNode(playerName);
    doc.appendChild(init);
    init.appendChild(playerJoined);
    playerJoined.appendChild(nameElem);
    nameElem.appendChild(nameText);
    return doc;
}
